package singleton;

/**
 * @Desc 懒汉式 双加锁
 * 需要时再初始化类
 * 多线程时仍不不适用
 * 双重检查
 * @Author: yaw
 * @Date: Created in 22:25 2021/7/20
 * @Version: 1.0
 */
public class Singleton5 {
    private static Singleton5 INSTANCE;

    private Singleton5() {
    }

    public static Singleton5 getInstance() {
        if (null == INSTANCE) {
            // 加锁在代码块
            synchronized (Singleton5.class) {
                if (null == INSTANCE){
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    INSTANCE = new Singleton5();
                }
            }
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                System.out.print(Singleton5.getInstance().hashCode() + "   ");
            }).start();
        }
    }
}
